package com.mindether.llyblog.advice;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Aspect
@Component
public class LogAdvice {

    private Logger logger= LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * com.mindether.llyblog.*..*(..))")
    public void webExptionLog(){
    }

    @Before("webExptionLog()")
    public void beforeCall(JoinPoint point){

    }

    @AfterThrowing(pointcut = "webExptionLog()",throwing = "ex")
    public void afterException(JoinPoint point,Throwable  ex){
        logger.info("调用出错--------");
        logger.error("出错信息为[{}]",ex.getMessage());
        ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        ServletRequest request=servletRequestAttributes.getRequest();
        ServletResponse response=servletRequestAttributes.getResponse();
        if(request!=null){
             Enumeration<String> attrNames= request.getAttributeNames();
             StringBuilder params=new StringBuilder();
            while (attrNames.hasMoreElements()){
                Object value=request.getAttribute(attrNames.nextElement());
                params.append(value.toString()+"--");
            }
            logger.error("接收的参数为[{}]",params);
        }
        try {
            request.getRequestDispatcher("/about").forward(request, response);
        }catch (IOException ioe){
            logger.error("请求处理异常--->{}",ioe.getMessage());
        }catch (ServletException se){
            logger.error("请求处理异常--->{}",se.getMessage());
        }
    }
}
